import '../../public.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import './slidableBar.dart';

class GroupList extends StatefulWidget {
  final String type;
  const GroupList(this.type, {super.key});

  @override
  State<GroupList> createState() => _GroupListState();
}

class _GroupListState extends State<GroupList> {
  @override
  Widget build(BuildContext context) {
    return ProviderWidget<UserModel>(
      builder: (context, model, child) {
        List<GAccountItem> accounts = [];
        for (var g in model.groups) {
          if (g.type == widget.type) {
            accounts.addAll(g.list);
          }
        }
        return CupertinoPageScaffold(
          navigationBar: const CupertinoNavigationBar(
            border: Border(bottom: BorderSide.none),
            backgroundColor: Colors.white,
            middle: Text('Account List'),
          ),
          child: SafeArea(
            child: Material(
              child: ListView.builder(
                itemCount: accounts.length,
                itemBuilder: (context, index) {
                  Category category =
                      AccountList.categories[accounts[index].type] as Category;
                  return SlidableBar(
                    onDelete: () {
                      model.deleteAccount(accounts[index].originKey);
                    },
                    child: ListTile(
                      onTap: () {
                        RouterHelper.navigator
                            .pushNamed(Routers.form, arguments: accounts[index])
                            .then((a) {
                              if (a == null) return;
                              model.editAccount(
                                a as GAccountItem,
                                accounts[index].originKey,
                              );
                            });
                      },
                      leading: Image.asset(category.src, width: 40, height: 40),
                      tileColor: Colors.white,
                      contentPadding: const EdgeInsets.symmetric(
                        vertical: 12,
                        horizontal: 15,
                      ),
                      title: Row(children: [Text('${accounts[index].name}')]),
                      subtitle: const Text('Swipe left to delete'),
                    ),
                  );
                },
              ),
            ),
          ),
        );
      },
      model: Provider.of<UserModel>(context),
    );
  }
}
